﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.Enum.MessageEnum;

namespace BLL.Manage
{
    public class NoticeManage
    {
        /// <summary>
        /// 获取社交消息
        /// </summary>
        public Model.Result<List<Model.ApiResult.NoticeResult.FriendsNoticeInfo>> GetSoicalMessageList(int pageNo, int pageSize)
        {
            UserManage userInfo = new UserManage();

            var sqlParamster = new MySql.Data.MySqlClient.MySqlParameter[] {
                new MySql.Data.MySqlClient.MySqlParameter("member_id",userInfo.UserTokenModel.MemberId)
            };
            var dateTable = MySqlDb.GetDataTable(@"
                SELECT
                    social_message.*,
                    A.nick_name as to_nick_name,
                    A.avatar as to_avatar,
                    B.nick_name as from_nick_name,
                    B.avatar as from_avatar
                FROM
                    social_message
                LEFT JOIN `user` AS A ON social_message.to_member_id = A.member_id
                LEFT JOIN `user` AS B ON social_message.from_member_id = B.member_id
                WHERE
                    social_message.to_member_id=@member_id or social_message.from_member_id=@member_id
                ORDER BY
                    social_message.create_time DESC;
            ",
           sqlParamster);
            List<Model.ApiResult.NoticeResult.FriendsNoticeInfo> list = new List<Model.ApiResult.NoticeResult.FriendsNoticeInfo>();
            for (int i = 0; i < dateTable.Rows.Count; i++)
            {
                var model = new Model.ApiResult.NoticeResult.FriendsNoticeInfo();
                var row = dateTable.Rows[i];
                model.FromMemberId = (string)row["from_member_id"];
                model.ToMemberId = (string)row["to_member_id"];
                model.MessageType = Convert.ToInt32(row["message_type"]);
                model.Extend = Convert.ToString(row["extend"]);
                model.IsRead = Convert.ToInt32(row["is_read"]);
                model.ReadTime = Convert.ToDateTime(row["read_time"]);
                model.CreateTime = Convert.ToDateTime(row["create_time"]);
                model.Rocial = Convert.ToInt32(row["rocial"]);
                model.IsHandle = Convert.ToInt32(row["is_handle"]);
                model.HandleResult = Convert.ToInt32(row["handle_result"]);
                model.MessageId = (string)row["message_id"];
                model.SendMessage = (string)row["send_message"];
                model.HandleMessage = Convert.ToString(row["handle_message"]);
                model.NickName = (string)row[model.FromMemberId == userInfo.UserTokenModel.MemberId ? "to_nick_name" : "from_nick_name"];
                model.Avatar = (string)row[model.FromMemberId == userInfo.UserTokenModel.MemberId ? "to_avatar" : "from_avatar"];
                list.Add(model);
            }
            return RestfulAPIModel.SuccessReult<List<Model.ApiResult.NoticeResult.FriendsNoticeInfo>>(list);
        }

        /// <summary>
        /// 发送消息给好友
        /// </summary>
        /// <param name="toMemberId"></param>
        /// <param name="content"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public Model.Result<Model.Entity.ChatMessage> SendSoicalMessageToFriend(string roomId, string content, int contentType)
        {
            UserManage userInfo = new UserManage();
            using (var context = new Model.Entity.DBContext())
            {
                var flag = false;
                // 通过memberid查询用户 注意是模糊查询 
                // var friends = new FriendsManage().SearchFriendListResult(toMemberId);
                // var findFriend = context.Friends.FirstOrDefault(p => p.FriendMemberId == toMemberId && p.MemberId == userInfo.UserTokenModel.MemberId);
                var findFriends = context.Friends.FirstOrDefault(p => p.FriendRelationId == roomId && p.MemberId == userInfo.UserTokenModel.MemberId);
                var model = new Model.Entity.ChatMessage()
                {
                    MessageId = System.Guid.NewGuid().ToString("N"),
                    SenderId = userInfo.UserTokenModel.MemberId,
                    ReceiverId = "",
                    Content = content,
                    //1：text 2：图片 3：语音   4：视屏
                    ContentType = contentType,
                    MessageType = 1,
                    IsRead = 0,
                    ReadTime = DateTime.Now,
                    CreateTime = DateTime.Now,
                    IsReceiver = 0,
                    ReceiverTime = DateTime.Now,
                    // 1 正常接收 2 拉黑无法接收 3 不是好友关系无法接收  4 未找到用户
                    ReceiverStatus = (int)MessageReceiverStatus.success,
                    ChatRoomId = roomId
                };
                // var findFriends = friends.Find(p => p.MemberId == toMemberId);
                if (findFriends == null)
                {
                    model.ReceiverStatus = (int)MessageReceiverStatus.notFoundUser;
                }
                // else   if (findFriends.FriendMemberId==)
                // {
                //     model.ChatRoomId = findFriends.FriendRelationId;
                //     model.ReceiverStatus = (int)MessageReceiverStatus.notFriend;
                // }
                else
                {
                    model.ReceiverId = findFriends.FriendMemberId;
                    context.ChatMessage.Add(model);
                    context.SaveChanges();
                    BLL.Wapper.WebSocketWapper.SendObjectAsync(model.ReceiverId, new Model.Basics.UserModel.SocketMessageTamplate()
                    {
                        SenderID = model.SenderId,
                        ReceiverID = model.ReceiverId,
                        SocketMessageType = SocketMessageType.friendChat,
                        Content = model,
                        ContentType = model.ContentType,
                        ChatRoomId = model.ChatRoomId
                    });
                    flag = true;
                    model.IsReceiver = 1;
                }
                if (flag)
                {
                    return RestfulAPIModel.SuccessReult<Model.Entity.ChatMessage>(model);
                }
                else
                {
                    return RestfulAPIModel.ErrorReult<Model.Entity.ChatMessage>(model);

                }
            }
        }
    }
}
